package com.rran.study.designpattern.behavioral.chain.repository;

import com.rran.study.designpattern.behavioral.chain.chain.ChainHandler;
import com.rran.study.designpattern.behavioral.chain.enums.AttackEnums;
import com.rran.study.designpattern.behavioral.chain.factory.ChainEnumFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yy
 * @Type ChainRepository.java
 * @Desc
 * @date 2020/7/20 15:43
 */
public class ChainRepository {
    public static Map<Integer, ChainHandler> chainHandlerMap = new ConcurrentHashMap<>();
    public static ChainHandler firstChain = null;

    static {
        AttackEnums[] values = AttackEnums.values();
        for (AttackEnums value : values) {
            ChainHandler chainHandler = ChainEnumFactory.getChainHandler(value);
            //将责任链缓存到map中
            chainHandlerMap.put(value.getHandlerId(), chainHandler);
            //设置责任链的头
            if (value.getIsHead() && firstChain == null) {
                firstChain = chainHandler;
            }
        }
        if (firstChain == null) {
            throw new RuntimeException("责任链必须设置头");
        }

        ChainHandler tempChain = firstChain;
        Integer next;
        //从头开始递归设置下一个链
        while ((next = tempChain.getNextChainId()) != null) {
            ChainHandler chainHandler = getChainHandler(next);
            tempChain.setNextChain(chainHandler);
            tempChain = chainHandler;
        }
    }

    public static ChainHandler getChainHandler(Integer handlerId) {
        return chainHandlerMap.get(handlerId);
    }

    public static ChainHandler getFirstChain() {
        return firstChain;
    }
}
